<template>
  <a-modal
    :title="title"
    :width="1000"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules" v-bind="layout">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-model-item label="选择员工" prop="employeeId">
              <j-select-employee-modal
                v-model="model.employeeId"
                :multiple="false"
                @change="handleEmployeeChange"
                placeholder="请选择员工"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="员工姓名">
              <a-input v-model="model.employeeName" disabled/>
            </a-form-model-item>
          </a-col>
        </a-row>
        
        <a-divider>工种分配</a-divider>
        
        <a-row>
          <a-col :span="24">
            <a-button type="dashed" @click="addWorkType" style="width: 100%; margin-bottom: 16px;">
              <a-icon type="plus" /> 添加工种
            </a-button>
            
            <a-table
              :columns="workTypeColumns"
              :dataSource="model.workTypes"
              :pagination="false"
              rowKey="workTypeId"
              size="small"
              bordered>
              
              <template slot="workTypeName" slot-scope="text, record, index">
                <a-select
                  v-model="record.workTypeId"
                  placeholder="请选择工种"
                  @change="(value) => handleWorkTypeChange(value, index)"
                  style="width: 100%">
                  <a-select-option
                    v-for="workType in workTypeOptions"
                    :key="workType.id"
                    :value="workType.id">
                    {{ workType.workTypeName }}
                  </a-select-option>
                </a-select>
              </template>
              
              <template slot="skillLevel" slot-scope="text, record">
                <j-dict-select-tag
                  v-model="record.skillLevel"
                  dictCode="skill_level"
                  placeholder="请选择技能等级"
                  style="width: 100%"/>
              </template>
              
              <template slot="certifier" slot-scope="text, record">
                <a-input v-model="record.certifier" placeholder="请输入认证人"/>
              </template>
              
              <template slot="remark" slot-scope="text, record">
                <a-input v-model="record.remark" placeholder="请输入备注"/>
              </template>
              
              <template slot="action" slot-scope="text, record, index">
                <a-popconfirm title="确定删除吗?" @confirm="() => removeWorkType(index)">
                  <a>删除</a>
                </a-popconfirm>
              </template>
            </a-table>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
  import { httpAction, getAction } from '@/api/manage'

  export default {
    name: 'EmployeeWorktypeAssignModal',
    components: {
    },
    data () {
      return {
        layout: {
          labelCol: {
            xs: { span: 24 },
            sm: { span: 5 },
          },
          wrapperCol: {
            xs: { span: 24 },
            sm: { span: 16 },
          },
        },
        title:"",
        visible: false,
        model: {
          employeeId: '',
          employeeName: '',
          workTypes: []
        },
        confirmLoading: false,
        workTypeOptions: [],
        workTypeColumns: [
          {
            title: '工种名称',
            dataIndex: 'workTypeName',
            width: '25%',
            scopedSlots: { customRender: 'workTypeName' }
          },
          {
            title: '技能等级',
            dataIndex: 'skillLevel',
            width: '15%',
            scopedSlots: { customRender: 'skillLevel' }
          },
          {
            title: '认证人',
            dataIndex: 'certifier',
            width: '20%',
            scopedSlots: { customRender: 'certifier' }
          },
          {
            title: '备注',
            dataIndex: 'remark',
            width: '30%',
            scopedSlots: { customRender: 'remark' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '10%',
            scopedSlots: { customRender: 'action' }
          }
        ],
        validatorRules: {
          employeeId: [
            { required: true, message: '请选择员工!' }
          ]
        },
        url: {
          assignEmployee: "/mes/employee-worktype/assign-employee",
          getAllWorkTypes: "/mes/worktype/all",
          getEmployeeWorkTypes: "/mes/employee-worktype/employee-worktypes"
        }
      }
    },
    created () {
      this.loadWorkTypes();
    },
    methods: {
      add () {
        this.edit({});
      },
      edit (record) {
        this.model = {
          employeeId: '',
          employeeName: '',
          workTypes: []
        };
        this.visible = true;
        if(!record.id){
          this.title = "员工工种分配";
        }else{
          this.title = "编辑员工工种分配";
          this.model.employeeId = record.employeeId;
          this.model.employeeName = record.employeeName;
          this.loadEmployeeWorkTypes(record.employeeId);
        }
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            if (this.model.workTypes.length === 0) {
              this.$message.warning('请至少添加一个工种分配');
              return;
            }
            
            that.confirmLoading = true;
            httpAction(this.url.assignEmployee, this.model, 'post').then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
                that.close();
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
        })
      },
      handleCancel () {
        this.close();
      },
      handleEmployeeChange(employeeId, employeeInfo) {
        this.model.employeeName = employeeInfo ? employeeInfo.empName : '';
        if (employeeId) {
          this.loadEmployeeWorkTypes(employeeId);
        }
      },
      loadWorkTypes() {
        getAction(this.url.getAllWorkTypes).then((res) => {
          if (res.success) {
            this.workTypeOptions = res.result || [];
          }
        });
      },
      loadEmployeeWorkTypes(employeeId) {
        getAction(`${this.url.getEmployeeWorkTypes}/${employeeId}`).then((res) => {
          if (res.success) {
            this.model.workTypes = (res.result || []).map(item => ({
              workTypeId: item.workTypeId,
              workTypeCode: item.workTypeCode,
              workTypeName: item.workTypeName,
              skillLevel: item.skillLevel,
              certifier: item.certifier,
              remark: item.remark
            }));
          }
        });
      },
      addWorkType() {
        this.model.workTypes.push({
          workTypeId: '',
          workTypeCode: '',
          workTypeName: '',
          skillLevel: 1,
          certifier: '',
          remark: ''
        });
      },
      removeWorkType(index) {
        this.model.workTypes.splice(index, 1);
      },
      handleWorkTypeChange(workTypeId, index) {
        const workType = this.workTypeOptions.find(item => item.id === workTypeId);
        if (workType) {
          this.model.workTypes[index].workTypeCode = workType.workTypeCode;
          this.model.workTypes[index].workTypeName = workType.workTypeName;
        }
      }
    }
  }
</script>
